import config from '@/conifg'

// 获取系统信息
export function sys() {
  return uni.getSystemInfoSync()
}

// 显示加载
export function showLoading(title = '') {
  uni.showLoading({
    title,
    mask: true,
  })
}

// 弹窗
export function showToast(title: string, onSuccess?: () => void) {
  const duration = 1500
  uni.showToast({
    title,
    icon: 'none',
    mask: true,
    duration,
    success: () => {
      if (typeof onSuccess === 'function') setTimeout(onSuccess, duration)
    },
  })
}

// 保存图片
export function uniSaveImage(filePath: string) {
  return new Promise((resolve, reject) => {
    uni.saveImageToPhotosAlbum({
      filePath,
      success: (res) => {
        resolve(res)
      },
      fail: (err) => {
        reject(err)
      },
    })
  })
}

export function saveImage(path) {
  uniSaveImage(path)
    .then((res) => {
      showToast('保存成功')
    })
    .catch((err) => {
      console.log(err, '保存失败')
      if (err.errMsg == 'saveImageToPhotosAlbum:fail auth deny') {
        openAuthorize('writePhotosAlbum', () => {
          saveImage(path)
        })
      }
    })
}

// 支付
export function requestPayment(orderInfo, provider = 'wxpay') {
  return new Promise((resolve, reject) => {
    uni.requestPayment({
      provider,
      // #ifndef MP-WEIXIN
      orderInfo,
      // #endif
      // #ifdef MP-WEIXIN
      ...orderInfo,
      // #endif
      success: (res) => {
        resolve(res)
      },
      fail: (err) => {
        reject(err)
      },
    })
  })
}

// 上传文件
export function uploadFile(
  filePath: string,
  options: Record<string, any>,
  onProgress?: (task: UniApp.UploadTask) => void,
) {
  // const suffix = options ? options.suffix : 'png'

  return new Promise((resolve, reject) => {
    const uploadTask = uni.uploadFile({
      url: config.uploadUrl,
      filePath,
      name: 'file',
      ...options,
      success: (res) => {
        const data = JSON.parse(res.data)

        if (data.code === 1) {
          resolve(data)
        } else {
          reject(data)
        }
      },
      fail: (err) => {
        reject(err)
      },
    })
    typeof onProgress === 'function' && onProgress(uploadTask)
  })
}

// #ifndef H5 || APP-PLUS || MP-ALIPAY
// https://uniapp.dcloud.io/api/other/authorize?id=scope-%e5%88%97%e8%a1%a8 查看scope键值
// 打开授权
export function openAuthorize(
  scopeKey: string,
  successCall: (isOk: number | boolean, result?: any) => void,
) {
  uni.getSetting({
    success: (auth) => {
      const flag = Object.keys(auth.authSetting).some(
        (key) => !!auth.authSetting[`scope.${scopeKey}`],
      )
      console.log(flag, '是否开启授1权', auth)
      if (!flag) {
        console.log('没有开启相关权限')
        uni.authorize({
          scope: `scope.${scopeKey}`,
          success: (r) => {
            console.log(r, '弹起授权')
            successCall(1)
          },
          fail: (e) => {
            console.log(e, '拒绝授权')
            uni.showModal({
              title: '提示',
              content: '授权失败,请点击确定重新授权!',
              success: (result) => {
                if (result.confirm) {
                  uni.openSetting({
                    success: (res) => {
                      if (res.authSetting[`scope.${scopeKey}`]) {
                        successCall(flag, res)
                      }
                    },
                  })
                }
              },
            })
          },
        })
      } else {
        successCall(flag)
      }
    },
  })
}
// #endif

// 获取图片临时路径
export function getImageBlobUrl(url: string) {
  return new Promise((resolve, reject) => {
    uni.getImageInfo({
      src: url,
      success: (res) => {
        resolve(res.path)
      },
      fail: (err) => {
        console.log(err, '获取图片临时路径失败')
        reject(err)
      },
    })
  })
}
